﻿/*----------------------------------------------------------------
// Copyright (C) 2016 通通优品版权所有。
// 命名空间: TongTongMall.MallWeb.Application.Users
// 类名：UserAppService
// 功能描述：N/A
// 
// 创建标识：Roc.Lee(李鹏鹏) 2017/8/29 11:16:23 TEC-ROCLEE Roc.Lee

// 修改标识：
// 修改描述：
// 
//
//----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using STOWaybillMall.Users.Dto;
using TongTongMall.MallWeb.Application.Users.Dto;
using TongTongMall.Domain.Repositories.Repositories;
using STOWaybillMall.Core;
using TongTongMall.MallWeb.Core.IRepositories;
using TongTongMall.MallWeb.Core.Enums;
using TEC.Public.Common;
using TongTongMall.MallWeb.Core.User.Services;
using TongTongMall.MallWeb.Core.Authorization.Models;
using TongTongMall.MallWeb.Core.User.Models;
using TongTongMall.MallWeb.Core.Identitys;
using TongTongMall.Oauth2._0.Models;

namespace TongTongMall.MallWeb.Application.Users
{
    public class UserAppService : MallWebApplicationServiceBase, IUserAppService
    {
        private readonly IRepository<UserBaseInfo, long> _UserBaseInfoRepository;
        private readonly IRepository<UserLoginRecord, long> _UserLoginRecordRepository;
        private readonly IUserBaseInfoRepository _IUserBaseInfoRepository;
        private readonly IUserDomainService _IUserDomainService;

        public UserAppService(
            IRepository<UserBaseInfo, long> _UserBaseInfoRepository, 
            IUserBaseInfoRepository _IUserBaseInfoRepository, 
            IUserDomainService _IUserDomainService,
            IRepository<UserLoginRecord, long> _UserLoginRecordRepository)
        {
            this._UserBaseInfoRepository = _UserBaseInfoRepository;
            this._IUserBaseInfoRepository = _IUserBaseInfoRepository;
            this._IUserDomainService = _IUserDomainService;
            this._UserLoginRecordRepository = _UserLoginRecordRepository;
        }



        public async Task<LoginSuccessOutput> Login(UserLoginInputDto input)
        {
            var resultData = new LoginSuccessOutput();

            //获取商户信息
            var tenantInfo = await TenantRedisManager.GetTenantInfo(Session.TenantName);
            if (tenantInfo == null)
            {
                throw new TongTongMallException("没有获取到商户在redis内的信息，请检查缓存服务器");
            }
            var userid = _IUserBaseInfoRepository.GetUserID(input.UserName);
            if (userid <= 0)
            {
                throw new UI.UserFriendlyException((int)ErrCode.AccountOrPwdErr, ErrCode.AccountOrPwdErr.GetEnumDescription(), new Exception($"{input.UserName}用户标识不存在"));

            }
            AccessTokenDto accesstoken = null;
            try
            {
                accesstoken = await _IUserDomainService.Authorization(new Core.User.Commands.UserLoginCommand
                {
                    Client = tenantInfo.Account,
                    ClientSecret = tenantInfo.Secret,
                    AuthorizationUrl = Instance.ApiConfig.OAuthUrl,
                    UserName = input.UserName,
                    Password = input.Pasword,
                    PlatForm = input.VisitPlatform.ToString(),
                    SessionKey = Session.SessionKey
                });
            }
            catch (Exception ex)
            {
                throw new UI.UserFriendlyException((int)ErrCode.AccountOrPwdErr, ErrCode.AccountOrPwdErr.GetEnumDescription(), new Exception($"{input.UserName}向授权服务器申请授权出错", ex));
            }
            LoginStatusEnum loginstatus = !string.IsNullOrEmpty(accesstoken.AccessToken) ? LoginStatusEnum.Success : LoginStatusEnum.Faild;
            UserLoginRecord record = new UserLoginRecord(input.VisitPlatform, loginstatus, LoginTypeEnum.Password, input.VisitInfo.IP, userid);
            record.OtherDetail = input.VisitInfo.OtherDetail;
            record.URI = input.VisitInfo.URI;
            record.Description = input.VisitInfo.Description;
            _UserLoginRecordRepository.Insert(record);
            if (loginstatus == LoginStatusEnum.Success)
            {
                //授权成功后从redis内获取用户信息
                var userCacheKey = RedisKeys.Instance.UserAuthorizationAfterRedisKey(Session.TenantName, $"{userid}", $"{input.VisitPlatform}");
                var userLoginInfo = await UserRedisManager.GetUserInfo<OAuthRedisUser>(userCacheKey);
                if (userLoginInfo == null) throw new UI.UserFriendlyException((int)ErrCode.ServerErr, "没有获取到授权之后的内容！");
                resultData.Key = accesstoken.AccessToken;
                resultData.ExpireTime = accesstoken.ExpiresIn;
                resultData.Expires = accesstoken.Expires;
                resultData.RefreshToken = accesstoken.RefreshToken;
                resultData.UseTime = accesstoken.IsSued;
            }
            else
            {
                throw new UI.UserFriendlyException((int)ErrCode.AccountOrPwdErr, ErrCode.AccountOrPwdErr.GetEnumDescription(), new Exception($"{input.UserName}用户授权失败"));
            }
            return resultData;
        }
    }
}
